package com.yznote.compileserver.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.yznote.compileserver.oss.OssClientPool;
import com.yznote.compileserver.oss.OssConfig;
import com.yznote.compileserver.pojo.Result;
import com.yznote.compileserver.yCompile.execute.YExecutor;
import com.yznote.compileserver.yCompile.io.YByteArrayInput;
import com.yznote.compileserver.yCompile.io.YInput;
import com.yznote.compileserver.yCompile.io.YOutPut;
import com.yznote.compileserver.yCompile.io.YResultOutPut;
import com.yznote.compileserver.yCompile.result.YResult;
import com.yznote.compileserver.yCompile.type.CodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;

@RestController
@RequestMapping("/compile")
public class CompileController {
    @Autowired
    OssClientPool ossClientPool;
    @Autowired
    OssConfig ossConfig;
    @Autowired
    YExecutor yExecutor;
    @RequestMapping("/run")
    public Result run(@RequestParam("fileName") String fileName,@RequestParam("filePath") String filePath) throws Exception{
        OSS ossClient = ossClientPool.getOssClient();
        OSSObject object = ossClient.getObject(ossConfig.getBuketName(), filePath);
        InputStream objectContent = object.getObjectContent();
        byte[] resp = new byte[1024*1024];
        int ind = 0;
        int len = 0;
        while((len=objectContent.read(resp,ind,resp.length-ind))!=-1){
            ind = ind+len;
        }
        resp = Arrays.copyOf(resp,ind);
        YInput yInput = new YByteArrayInput(resp);
        YResult yResult = new YResult();
        YOutPut yOutPut = new YResultOutPut(yResult);
        yExecutor.execute(yInput, yOutPut,CodeType.JAVA,"F:\\"+fileName,fileName);
        yInput.close();
        yOutPut.close();
        return Result.sussess(yResult,"执行任务成功");
    }


}
